package com.dotools.privacy;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dotools.procommon.R;
import com.dotools.umlibrary.UMPostUtils;
import com.dotools.utils.FileUtils;
import com.dotools.utils.NetWorkUtils;
import com.dotools.utils.PackageUtils;
import com.tools.permissions.library.DOPermissions;
import com.tools.permissions.library.Permissions;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

public class WebFeedBackActivity extends AppCompatActivity implements DOPermissions.DOPermissionsCallbacks {

    private ImageView mBack;
    private WebView webView;
    private RelativeLayout mTopLayout;
    private int FILECHOOSER_RESULTCODE = 23;
    ///图片上传///
    private ValueCallback<Uri[]> mUploadMsgForAndroid5;
    private ValueCallback<Uri> mUploadMsg;
    private String[] pers = new String[]{Permissions.READ_EXTERNAL_STORAGE, Permissions.WRITE_EXTERNAL_STORAGE};

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_feed_back);
        mBack = findViewById(R.id.web_ido_feed_back);
        webView = findViewById(R.id.web_feed_webview);
        mTopLayout = findViewById(R.id.web_feed_title_layout);

        checkTopLayout();

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        if (NetWorkUtils.isNetworkAvaialble(getApplicationContext())) {
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setSavePassword(false);//明文密码漏洞配置
            webView.getSettings().setAllowFileAccess(false);//同源策略绕过
            webView.getSettings().setDomStorageEnabled(true);       // 这个要加上
            /* 获得 webview url，请注意url单词是product而不是products，products是旧版本的参数，用错地址将不能成功提交 */
            String url = "https://support.qq.com/product/" + getId();
            /* 准备post参数 */
            final String postData = "osVersion=" + Build.VERSION.SDK_INT + "&clientInfo=" + android.os.Build.MODEL + "&clientVersion=" + PackageUtils.getVersionName(getApplicationContext(), getPackageName());
            /* WebView 内嵌 Client 可以在APP内打开网页而不是跳出到浏览器 */
            WebViewClient webViewClient = new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    super.shouldOverrideUrlLoading(view, url);
                    if (url == null) {
                        return false;
                    }
                    try {
                        if (url.startsWith("weixin://")) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            view.getContext().startActivity(intent);
                            return true;
                        }
                    } catch (Exception e) {
                        return false;
                    }
                    view.loadUrl(url);
                    return true;
                }
            };
            webView.setWebViewClient(webViewClient);
            webView.setWebChromeClient(new XHSWebChromeClient());
            webView.postUrl(url, postData.getBytes());
        } else {
            Toast.makeText(getApplicationContext(), "请连接网络", Toast.LENGTH_SHORT).show();
        }

        if (!DOPermissions.getInstance().hasPermission(this, pers)) {
            DOPermissions.getInstance().getPermissions(this, "意见反馈的图片上传功能需要存储权限", 11, pers);
        }
    }

    /**
     * 设置title是否显示
     * intent 中设置 isShowTitle 为false 为不显示
     * 不设置 或者设置true 为显示
     **/
    private void checkTopLayout() {
        if (getIntent() != null && !getIntent().getBooleanExtra("isShowTitle", true)) {
            mTopLayout.setVisibility(View.GONE);
        } else {
            mTopLayout.setVisibility(View.VISIBLE);
        }
    }

    private String getId() {
        switch (getPackageName()) {
            case "com.ibox.calculators":
                return "340321";
            case "com.ido.screen.record":
                return "280300";
            case "com.dotools.note":
                return "302992";
            case "com.one.click.ido.screenshot":
                return "290119";
            case "com.ido.oneclick.screenCutImg":
                return "297855";
            case "com.sydo.perpetual.calendar":
                return "297879";
            case "com.ido.barrage":
                return "293522";
            case "com.syido.voicerecorder":
                return "311483";
            case "com.syido.extractword":
                return "296338";
            case "com.ido.screen.record.expert":
                return "351522";
            case "com.chacha.qrcode":
                return "297105";
            case "com.ido.oneclick.screenshotHelper":
                return "343085";
            case "com.ibox.flashlight":
                return "298983";
            case "com.idotools.rings":
                return "299128";
            case "com.ido.ruler":
                return "299207";
            case "com.ido.projection":
                return "300678";
            case "com.syido.idoreplaceicon":
                return "303411";
            case "com.idoconstellation":
                return "302966";
            case "com.ltt.compass":
                return "303087";
            case "com.dotools.weather":
                return "302003";
            case "com.almighty.calculators":
                return "343155";
            case "com.rongyao.clock":
                return "304274";
            case "com.ido.eye.protection":
                return "312520";
            case "com.oeiskd.easysoftkey":
                return "319922";
            case "com.sydo.longscreenshot":
                return "313930";
            case "com.qiongyou.compass":
                return "303995";
            case "com.qimeng.naoli":    //幼儿脑力思维启蒙
                return "303008";
            case "com.study.hanzi":     //一起学写汉字
                return "303007";
            case "com.parental.controler":  //儿童锁
                return "304245";
            case "com.bookstory.renge":     //人格
                return "305624";
            case "com.diantai.youer":     //幼儿情感电台
                return "303514";
            case "com.ac.pbook":    //儿童绘本故事机
                return "299572";
            case "com.idostudy.mathematicss":    //小学数学
                return "298459";
            case "com.idostudy.picturebook":    //儿童绘本故事
                return "297528";
            case "com.idostudy.babyw":    //宝宝知识星球
                return "296912";
            case "com.idostudy.chengyu":    //成语故事
                return "295729";
            case "com.idostudy.shici":    //古诗词启蒙
                return "295397";
            case "com.syido.fmod":    //宝宝知识星球
                return "280301";
            case "com.qimeng.math":
                return "305854";
            case "com.ido.watermark.camera":
                return "323490";
            case "com.idotools.qrcode":
                return "308427";
            case "com.dotools.nightcamera":
                return "308215";
            case "com.syido.timer":
                return "308299";
            case "com.iboxltt.flashlight":
                return "311493";
            case "com.dotools.clock":
                return "311522";
            case "com.idostudy.enstory":
                return "313241";
            case "com.idostudy.picture":
                return "313243";
            case "com.syido.weightpad":
                return "313758";
            case "com.ido.shadow":
                return "314261";
            case "com.sydo.subtitlesadded":
                return "363187";
            case "com.syido.changeicon":
                return "315670";
            case "com.second.stepcount":
                return "315810";
            case "com.syd.stepcount":
                return "315811";
            case "com.sydo.audioextraction":
                return "340699";
            case "com.readily.calculators":
                return "341452";
            case "com.sydo.idphoto":
                return "342860";
            case "com.syido.tips":
                return "318889";
            case "com.idostudy.enword":
                return "318868";
            case "com.pocket.calculators":
                return "340628";
            case "com.idostudy.chinese":
                return "322313";
            case "com.study.privatestudy":
                return "325882";
            case "com.sydo.privatedomain":
                return "327338";
            case "com.idostudy.gushi":
                return "327359";
            case "com.story.chengyu":
                return "329743";
            case "com.sydo.puzzle":
                return "335140";
            case "com.sydo.onekeygif":
                return "335488";
            case "com.study.dizigui":
                return "324899";
            case "com.idostudy.errorbook":
                return "336310";
            case "com.syid.measure":
                return "340054";
            case "com.fk.decibel":
                return "340069";
            case "com.ido.compass":
                return "340333";
            case "com.quna.compass":
                return "344060";
            case "com.neihan.clock":
                return "345555";
            case "com.syido.express":
                return "346343";
            case "com.syido.rhythm":
                return "346759";
            case "com.sydo.re.watermark":
                return "347098";
            case "com.syido.netradio":
                return "347546";
            case "com.erciyuan.clock":
                return "349086";
            case "com.idotools.magnifier":
                return "344333";
            case "com.syido.decibel":
                return "352806";
            case "com.syido.idotask":
                return "360154";
            case "com.koudai.qrcode":
                return "362027";
            case "com.idopartx.phonelightning":
                return "405926";
            default:
                finish();
                startActivity(new Intent(WebFeedBackActivity.this, FeedBackActivity.class));
                return "0";
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        UMPostUtils.INSTANCE.onActivityResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        UMPostUtils.INSTANCE.onActivityPause(this);
//        try {
//            InputMethodManager manager = ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE));
//            if (manager != null)
//                manager.hideSoftInputFromWindow(edit.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//        }catch (Exception e){
//
//        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            if (requestCode == FILECHOOSER_RESULTCODE) {
                if (mUploadMsg != null) {
                    mUploadMsg.onReceiveValue(null);
                }

                if (mUploadMsgForAndroid5 != null) {         // for android 5.0+
                    mUploadMsgForAndroid5.onReceiveValue(null);
                }
            }
        }
        try {
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result == null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mUploadMsgForAndroid5.onReceiveValue(null);
                } else {
                    mUploadMsg.onReceiveValue(null);
                }
                mUploadMsg = null;
                mUploadMsgForAndroid5 = null;
                return;
            }
            String path = FileUtils.getPath(this, result);
            if (TextUtils.isEmpty(path)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mUploadMsgForAndroid5.onReceiveValue(null);
                } else {
                    mUploadMsg.onReceiveValue(null);
                }
                mUploadMsg = null;
                mUploadMsgForAndroid5 = null;
                return;
            }
            Uri uri = Uri.fromFile(new File(path));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
            } else {
                mUploadMsg.onReceiveValue(uri);
            }
            mUploadMsg = null;
            mUploadMsgForAndroid5 = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class XHSWebChromeClient extends WebChromeClient {
        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMsg = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
            i.setType(type);
            startActivityForResult(Intent.createChooser(i, "选择图片"), FILECHOOSER_RESULTCODE);
        }

        //Android 5.0+
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadMsgForAndroid5 = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null && fileChooserParams.getAcceptTypes().length > 0) {
                i.setType(fileChooserParams.getAcceptTypes()[0]);
            } else {
                i.setType("*/*");
            }
            startActivityForResult(Intent.createChooser(i, "选择图片"), FILECHOOSER_RESULTCODE);
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DOPermissions.getInstance().setRequestPermission(this, requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull @NotNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull @NotNull List<String> perms) {

    }

}
